package com.player;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.player.dao.DAOLocator;
import com.player.jsp.SessionBean;

public class LoginFilter implements Filter {

	private boolean debugMode = false;

	public void init(FilterConfig config) throws ServletException {
		String debug = config.getInitParameter("debug");
		if (debug != null) {
			debugMode = Boolean.parseBoolean(debug);
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {

		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest) request;
			String url = req.getRequestURL().toString();

			// FIXME disgusting hack
			if (url.endsWith("main.jsp") || url.endsWith("register.jsp") || url.contains("/html/")
					|| url.contains("/rest/") || url.endsWith("/")) {
				UserService userService = UserServiceFactory.getUserService();
				User user = userService.getCurrentUser();

				SessionBean sessionBean = getCreateSessionBean(req.getSession());
				String pageUri = "/tables.jsp"; // FIXME get from configuration requestUriToPageUri
				sessionBean.setDebug(debugMode);
				sessionBean.setPageUri(pageUri);
				if (isLoggedIn(user)) {
					sessionBean.setUserSwitched(isSwitchedUser(user.getEmail(), sessionBean.getEmail()));
					sessionBean.setEmail(user.getEmail());
					sessionBean.setRegistered(isRegistered(user.getEmail()));
				} else {
					// FIXME move to sessionbean
					sessionBean.setEmail("");
					sessionBean.setRegistered(false);
					sessionBean.setUserSwitched(false);
				}

			}
		}

		// proceed along the chain
		chain.doFilter(request, response);
	}

	public void destroy() {
	}

	@Deprecated
	private boolean isSwitchedUser(String currentlyLoggedInEmail, String sessionEmail) {
		return currentlyLoggedInEmail != null && sessionEmail != null && !currentlyLoggedInEmail.equals(sessionEmail);
	}

	private boolean isLoggedIn(User user) {
		return user != null;
	}

	private SessionBean getCreateSessionBean(HttpSession session) {
		SessionBean sessionBean = (SessionBean) session.getAttribute("playerSession");

		if (sessionBean == null) {
			sessionBean = new SessionBean();
			session.setAttribute("playerSession", sessionBean);
		}

		return sessionBean;
	}

	private boolean isRegistered(String email) {
		return DAOLocator.getPlayerDAO().existsEmail(email);
	}
}
